<?php
class Comments extends Dao
{
	private static $_instance = null;
	protected $_db = null, $_cache = null;
	
	protected function __construct()
	{
		parent::__construct();
	}
	
	public static function getInstance() 
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	
	public function listComments($postId, array $args = array())
	{
		if(empty($postId)) throw Exception('Invalid Input');
		$defaults = array(
			'comment_status'=>null,
			'page' => 1,
			'limit' => MIN_ROWS_PER_PAGE,
			'order_by' => 'comment_id',
			'order' => 'DESC'
		);
		$args = $this->args_merge($defaults, $args);
		$intPage = $args['page'];
		$intLimit = $args['limit'];
		$intStart = ($intPage-1)*$intLimit;
		try{
			$strSql = " SELECT *
						FROM tbl_cms_comments
						WHERE post_id=:pid
						ORDER BY {$args['order_by']} {$args['order']}
						LIMIT :intStart, :intLimit";
			$cmd = $this->_db->createCommand($strSql);
			$cmd->bindParam(":pid",$postId,PDO::PARAM_STR);
			$cmd->bindParam(":intStart",$intStart,PDO::PARAM_INT);
			$cmd->bindParam(":intLimit",$intLimit,PDO::PARAM_INT);
			return $arrResults = $cmd->queryAll();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function insertComment($postId, array $args)
	{
		if(empty($postId)) throw Exception('Invalid Input');
		$defaults = array(
			'comment_title' => null,
			'comment_body' => null,
			'comment_created_date' => new CDbExpression('NOW()'),
			'comment_creator_id' => null,
			'comment_creator_name' => null,
			'comment_creator_email' => null,
			'comment_creator_ip' => null,
			//'comment_last_modified_date' => null,
			//'comment_last_modifier_id' => null,
			'comment_parent' => null,
			'comment_status' => 0
		);
		$args = $this->args_merge($defaults, $args);
		$args['post_id'] = $postId;
		try{
			$cmd = $this->_db->createCommand();
			$cmd->insert('tbl_cms_comments',$args);
			return Yii::app()->db->getLastInsertId();
		} catch(Exception $ex){
			throw new Exception($ex->getMessage());
		}
	}
	
	public function getComment($commentId)
	{
	
	}
	
	public function deleteComment($commentId)
	{
	
	}
}